package com.qf.cx.simplenms.reader.model;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import com.qf.cx.simplenms.common.utils.SetUtils;
import com.qf.cx.simplenms.link.api.LinkManager.ReaderSource;

public class ReaderModel {
	private String name;
	private ReaderSource readerSource;
	private final Set<AntennaModel> antennas = new CopyOnWriteArraySet<>();

	public synchronized void setReaderSource(ReaderSource readerSource) {
		this.readerSource = readerSource;
	}

	public synchronized ReaderSource getReaderSource() {
		return readerSource;
	}

	public synchronized int getLinkType() {
		return readerSource.getLinkType().getValue();
	}

	public synchronized String getDeviceSn() {
		return readerSource.getDeviceSn();
	}

	public synchronized String getName() {
		return name;
	}

	public synchronized void setName(String name) {
		this.name = name;
	}

	public synchronized Set<AntennaModel> getAntennas() {
		return new HashSet<>(antennas);
	}

	public synchronized String getIp() {
		return readerSource.getIp();
	}

	public synchronized int getPort() {
		return readerSource.getPort();
	}

	private void deleteAntennas(Set<AntennaModel> dels) {
		this.antennas.removeAll(dels);
	}

	public synchronized void addAntennas(Set<AntennaModel> adds) {
		this.antennas.addAll(adds);
	}

	public synchronized ReaderSource update(ReaderModel newReaderModel) {
		Set<AntennaModel> news = newReaderModel.getAntennas();
		ReaderSource needClean = null;

		if (!this.readerSource.equals(newReaderModel.getReaderSource())) {
			needClean = this.readerSource;
			this.readerSource = newReaderModel.getReaderSource();
		}
		Set<AntennaModel> olds = antennas;
		Set<AntennaModel> dels = SetUtils.getComplementary(olds, news);
		deleteAntennas(dels);

		Set<AntennaModel> adds = SetUtils.getComplementary(news, olds);
		addAntennas(adds);
		return needClean;
	}

	@Override
	public String toString() {
		return "ReaderModel [name=" + name + ", readerSource=" + readerSource + ", antennas=" + antennas + "]";
	}

}
